package cn.hello2018.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author jeymingwu
 * @date 2019/3/8 11:54
 */
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("已接收到请求");

        // 从request当中获取流信息
        InputStream fileSource = req.getInputStream();
        String tempFileName = "D:/tempFile";
        // tempFile指向临时文件
        File tempFile = new File(tempFileName);
        // outputStream 文件输出流指向这个临时文件
        FileOutputStream outputStream = new FileOutputStream(tempFile);
        byte[] b = new byte[1024];
        int n;
        while ((n = fileSource.read(b)) != -1)  {
            outputStream.write(b, 0, n);
        }
        // 关闭输出流、输入流
        outputStream.close();
        fileSource.close();

        // 获取上传文件的名称
        RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "r");
        randomAccessFile.readLine();
        String str = randomAccessFile.readLine();
        int beginIndex = str.lastIndexOf("\\") + 1;
        int endIndex = str.lastIndexOf("\"");
        String filename = str.substring(beginIndex, endIndex);
        System.out.println("filename:" + filename);

        // 重新定位文件指针到文件头
        randomAccessFile.seek(0);
        long startPosition = 0;
        int i = 1;
        // 获取文件内容，开始位置
        while ((n = randomAccessFile.readByte()) != -1 && i <= 4) {
            if (n == '\n') {
                startPosition = randomAccessFile.getFilePointer();
                ++i;
            }
        }
        // startPosition = startPosition - 1;

        // 获取文件结束位置
        randomAccessFile.seek(randomAccessFile.length());
        long endPosition = randomAccessFile.getFilePointer();
        int j = 1;
        while (endPosition >= 0 && j <= 2) {
            endPosition--;
            randomAccessFile.seek(endPosition);
            if (randomAccessFile.readByte() == '\n') {
                ++j;
            }
        }
        endPosition = endPosition - 1;

        // 设置保存上传文件的路径
        String realPath = getServletContext().getRealPath("/") + "images";
        File fileUpload = new File(realPath);
        if (!fileUpload.exists()) {
            fileUpload.mkdir();
        }
        File saveFile = new File(realPath, filename);
        RandomAccessFile randomAccessOtherFile = new RandomAccessFile(saveFile, "rw");
        // 从临时文件当中读取文件内容（根据起止位置获取）
        randomAccessFile.seek(startPosition);
        while (startPosition < endPosition) {
            randomAccessOtherFile.write(randomAccessFile.readByte());
            startPosition = randomAccessFile.getFilePointer();
        }
        // 关闭输入输出流、 删除临时文件
        randomAccessFile.close();
        randomAccessOtherFile.close();
        tempFile.delete();

        req.setAttribute("result", "上传成功");
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/jsp/uploadImage.jsp");
        requestDispatcher.forward(req, resp);

    }
}
